package org.cuckoocs.xyfile.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class XYFileHeader extends ByteFile {

	static {
		size = (new XYFileHeader().toByte()).length;
	}
	
	public static final int size;
	
	private long indexOffset;
	private long indexLength;
	private long dataOffset;
	private long dataLength;

	private XYFileHeader(){
	}
	
	public XYFileHeader(byte[] bytes) {
		repair(bytes);
	}

	public XYFileHeader(long indexOffset, long indexLength, long dataOffset,
			long dataLength) {
		super();
		this.indexOffset = indexOffset;
		this.indexLength = indexLength;
		this.dataOffset = dataOffset;
		this.dataLength = dataLength;
	}
	
	public void addDataLength(long len){
		this.dataLength += len;
	}
	
	public long getIndexOffset() {
		return indexOffset;
	}

	public void setIndexOffset(long indexOffset) {
		this.indexOffset = indexOffset;
	}

	public long getIndexLength() {
		return indexLength;
	}

	public void setIndexLength(long indexLength) {
		this.indexLength = indexLength;
	}

	public long getDataOffset() {
		return dataOffset;
	}

	public void setDataOffset(long dataOffset) {
		this.dataOffset = dataOffset;
	}

	public long getDataLength() {
		return dataLength;
	}

	public void setDataLength(long dataLength) {
		this.dataLength = dataLength;
	}

	@Override
	public byte[] toByte() {
		byte[] buff = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try (DataOutputStream dos = new DataOutputStream(baos)) {
			dos.writeLong(this.indexOffset);
			dos.writeLong(this.indexLength);
			dos.writeLong(this.dataOffset);
			dos.writeLong(this.dataLength);

			buff = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buff;
	}

	@Override
	public void repair(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		try (DataInputStream dis = new DataInputStream(bais)) {
			this.indexOffset = dis.readLong();
			this.indexLength = dis.readLong();
			this.dataOffset = dis.readLong();
			this.dataLength = dis.readLong();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return "XYFileHeader [indexStart=" + indexOffset + ", indexLength="
				+ indexLength + ", dataStart=" + dataOffset + ", dataLength="
				+ dataLength + "]";
	}

}
